package cn.edu.zstu.qingzhu.qingzhushop.controller;

import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import cn.edu.zstu.qingzhu.qingzhushop.entity.Seckill;
import cn.edu.zstu.qingzhu.qingzhushop.service.ISeckillService;
import cn.edu.zstu.qingzhu.qingzhushop.service.impl.SeckillServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * FileName: SeckillController
 *
 * @Author: LvYibin
 * @Date: 2021/5/17 09:36
 * @Description:
 */
@RestController
@RequestMapping("/seckill")
public class SeckillController {
    private static final Logger log = LoggerFactory.getLogger(SeckillController.class);
    @Autowired
    private ISeckillService seckillService;
    @Autowired
    private ObjectMapper objectMapper;

    @RequestMapping(value = "/hand/out",method = RequestMethod.POST)
    public ResponseBean handout(@RequestBody Seckill seckill){
        try{
            String killId = seckillService.handout(seckill);
            return ResponseBean.success(killId);
        } catch (Exception e) {
            log.error("发布秒杀发生异常：seckill={}",seckill,e.fillInStackTrace());
            return ResponseBean.error("发布秒杀发生异常");
        }

    }

    @RequestMapping(value = "/rob",method = RequestMethod.GET)
    public ResponseBean robRedPacket(@RequestParam Integer userId, @RequestParam String killId){
        try {
            int result = seckillService.rob(userId,killId);
            if (result==0){
                return ResponseBean.error("抢购未开始或者已经结束");
            }else if(result==1){
                return ResponseBean.success("抢购成功，请尽快付款");
            }else if(result==2){
                return ResponseBean.error("商品已被抢购完");
            }else {
                return ResponseBean.error("您已经抢购过商品了");
            }
        }catch (Exception e){
            log.error("抢购发生异常：userId={},killId={}",userId,killId,e.fillInStackTrace());
            return ResponseBean.error(e.getMessage());
        }

    }
}
